package com.qf.service.serviceImpl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import com.qf.pojo.UserResp;
import com.qf.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    JavaMailSender javaMailSender;
    @Value("479422316@qq.com")
    private String from;
    @Override
    public String sendMail(String mail, HttpServletRequest req) {
        //声明simplemailMessage
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //发送者
        simpleMailMessage.setFrom(from);
        //接受者
        simpleMailMessage.setTo(mail);
        //内容
        Random re=new Random();
        String code="";
        for (int a=0;a<4;a++){
            int i = re.nextInt(9);
            code+=i;
        }
        simpleMailMessage.setText(code);
        //主题
        simpleMailMessage.setSubject("邮箱验证");
        //发送
        javaMailSender.send(simpleMailMessage);
        HttpSession session = req.getSession();
        session.setAttribute(mail,code);

        return "success";
    }

    @Override
    public String registry(UserResp userResp, HttpServletRequest req) {
        String mail = userResp.getEmail();
        String code = userResp.getCode();
        //从session获取到发送的验证码进行对比
        HttpSession session = req.getSession();
        String attribute = (String) session.getAttribute(mail);
        if (code.equals(attribute)){
            //用户输入的验证码跟我们发送的验证码一致
            //将数据存储到数据库中
            User user=new User();

            //将第一个对象的值复制给第二个对象中
            BeanUtils.copyProperties(userResp,user);
            userDao.saveAndFlush(user);

            return "success";
        }
        return "fail";
    }

    @Override
    public User login(User user) {
        return userDao.findByNumberAndPassword(user.getNumber(),user.getPassword());
    }
}
